import { init } from 'snabbdom/build/package/init'
import { classModule } from 'snabbdom/build/package/modules/class'
import { propsModule } from 'snabbdom/build/package/modules/props'
import { styleModule } from 'snabbdom/build/package/modules/style'
import { eventListenersModule } from 'snabbdom/build/package/modules/eventlisteners'
import { h } from 'snabbdom/build/package/h' // helper function for creating vnodes
import data from './data.js';
var patch = init([ classModule, propsModule, styleModule, eventListenersModule ]);
var nextKey = 11;
var vnode;

// 删除一个li
function remove(movie) {
    data = data.filter((m) => {
        return m !== movie
      })
      render()
}
// 电影列表渲染函数
function movieList(movie) {
    return h('div.row', {
        key: movie.rank,
    }, [
        h('div', movie.rank),
        h('div', movie.title),
        h('div', movie.desc),
    ])
}
// 获取列表函数
function getView(data) {
    return h('div', [
        h('h1', '电影列表'),
        h('div', [
            h('a.btn.add', { on: { click: addItem}}, '添加一项'),
            h('button.btn.rank',{ on: {click: [changeSort, 'rank']}},'排序'),
            h('button.btn.title',{ on: {click: [changeSort, 'title']}},'按标题'),
            h('button.btn.desc',{ on: {click: [changeSort, 'desc']}},'按描述')
        ]),
        h('div.list',{}, data.map(movieList))
    ])
}
// 添加一项
function addItem () {
    let rank = (data[data.length - 1].rank) + 1
    data.push({ rank: rank, title: `新增数据${rank}`, desc: `新增数据${rank}.....`, elmHeight: 0 })
    render()
}
// 排序点击函数
function changeSort(sortBy) {
    data.sort((a, b) => {
        if(a[sortBy] > b[sortBy]) {
            return 1
        }
        if(a[sortBy] < b[sortBy]) {
            return -1;
        }
        return 0;
    });
    console.log(data)
    render()
}
// 渲染函数
function render() {
    vnode = patch(vnode,getView(data))
}
// 添加html 文档被完全加载和解析以后
window.addEventListener('DOMContentLoaded', () => {
    var container = document.getElementById('container');
    vnode = patch(container, getView(data))
    render()
})